import axios from "axios";
import {ElMessage} from "element-plus";
import { useRouter } from 'vue-router'
import {ref} from 'vue'

const  baseUrl = 'http://localhost:8090';

const  instance = axios.create({
    baseURL: baseUrl,
    timeout: 6000,
    withCredentials:true
})

// 在实例上设置请求拦截器
instance.interceptors.request.use(config => {
    // 在请求头中添加token
    config.headers.JWT = getToken();
    return config;
}, error => {
    // 请求错误处理
    return Promise.reject(error);
});


const jwt = ref("");

const setToken=(tk)=>{
    jwt.value = tk;
    window.localStorage.setItem("jwt",jwt.value)
}

const getToken=()=>{
    let tk =  jwt.value;
    if (tk == undefined || tk.length <=1){
      let v = window.localStorage.getItem("jwt");
      if (v != undefined && v.length > 1){
          jwt.value = v;
      }
    }
    return jwt.value;

}

const aop = (fun) => {
    return new Promise((resolve, reject) => {
        let result = fun();
        result.then(response => {
            let data = response.data;
            if (data.data != undefined && data.data.token != undefined && data.data.token != '') {
               setToken(data.data.token);
            }
            if (data.code == 4003 && window.location.pathname != '/') {
                window.location.href = '/'
            } else if (data.code != 0) {
                ElMessage.error(data.msg);
            }
            resolve(data);
        }).catch((er)=>reject(er));
    })
}
const http = {
    GET: (url,params)=>{
          return aop(()=> instance.get(url,{params:params}));
    },
    POST: (url,data)=>{
        return aop(()=> instance.post(url,data));
    },
    logout(){
        jwt.value = "";
        window.localStorage.removeItem("jwt");
    },
    randomCode(){
        return baseUrl +"/code?t="+(new Date).getTime();
    },
    genUrl(url){
        return baseUrl +url;
    }
}

export default http;